<template>
  <Dialog
    v-model="showModel"
    title="优惠券配置"
    :loading="submitLoading"
    close-on-click-modal
    width="800px"
    destroy-on-close
    @opened="handleOpened"
    @confirm="saveCouponSetting"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      :label-width="130"
    >
      <el-form-item
        label="优惠券名称："
        prop="name"
      >
        <el-input
          v-model="form.name"
          placeholder="请输入优惠券名称"
          maxlength="100"
          show-word-limit
          @blur="handleBlur(form, 'name')"
        />
      </el-form-item>
      <el-form-item label="优惠券类型：">
        {{ getCouponTypeName(couponDetail?.couponType) }}
      </el-form-item>
      <el-form-item label="优惠券规则：">
        <template v-if="couponDetail?.couponType === 1">
          消费满{{ couponDetail?.discountRule?.fullPrice }}元，立减{{ couponDetail?.discountRule?.reducePrice }}元
        </template>
        <template v-if="couponDetail?.couponType === 2">
          消费满{{ couponDetail?.discountRule?.fullPrice }}，可享受折扣{{ couponDetail?.discountRule?.discount }}折（折扣比例:原价为1，0.99即为九九折）
        </template>
        <template v-if="couponDetail?.couponType === 3">
          使用范围商品任选一件兑换
        </template>
      </el-form-item>
      <el-form-item label="使用范围：">
        <template v-if="couponDetail?.useRange === 1">
          {{ getCouponUseRangeLabel(couponDetail?.useRange) }} {{ couponDetail?.businessName ? `(${couponDetail?.businessName})` : '' }}
        </template>

        <!-- 活动不应该出现商城类的优惠券，所以不需要显示商城类型相关的useRange -->
        <!-- <template v-if="couponDetail?.useRange === 2"> -->
        <!-- {{ getCouponUseRangeLabel(couponDetail?.useRange) }}  -->
        <!-- ({{ mallConfig.mallName }}) -->
        <!-- </template> -->

        <!-- <template v-if="couponDetail?.useRange === 3"> -->
        <!-- {{ getCouponUseRangeLabel(couponDetail?.useRange) }}  -->
        <!-- ({{ mallConfig.mallName }} - 部分商品) -->
        <!-- </template> -->

        <!-- <template v-if="couponDetail?.useRange === 4"> -->
        <!-- {{ getCouponUseRangeLabel(couponDetail?.useRange) }}  -->
        <!-- ({{ mallConfig.mallName }} - 部分商品分类) -->
        <!-- </template> -->
      </el-form-item>
      <el-form-item label="领取时间：">
        {{ formatTime(couponDetail?.receiveStartTime) }} 至 {{ formatTime(couponDetail?.receiveEndTime) }}
      </el-form-item>
      <el-form-item>
        <div v-if="couponDetail?.receiveType === 0">
          领取时间内，均可领取
        </div>
        <div v-if="couponDetail?.receiveType === 1">
          领取时间内，每天{{ couponDetail?.receiveRangeStartTime }} 至 {{ couponDetail?.receiveRangeEndTime }} 
        </div>
        <div v-if="couponDetail?.receiveType === 2">
          领取时间内，每周 {{ couponDetail?.receiveWeekDay }} {{ couponDetail?.receiveRangeStartTime }} 至 {{ couponDetail?.receiveRangeEndTime }} 
        </div>
        <div v-if="couponDetail?.receiveType === 3">
          领取时间内，每月 {{ couponDetail?.receiveMonth }} 日 {{ couponDetail?.receiveRangeStartTime }} 至 {{ couponDetail?.receiveRangeEndTime }} 
        </div>
      </el-form-item>
      <el-form-item label="优惠券图片：">
        <Upload
          v-model="form.thumbnailUrl"
          list-type="picture-card"
          file-path="pointsMall/"
        >
          <el-icon>
            <Plus />
          </el-icon>
        </Upload>
      </el-form-item>

      <el-form-item
        label="售价："
        prop="salePrice"
        class="form-item-price"
      >
        <!-- <div > -->
        <el-input
          v-model="form.currencyNum"
          placeholder="请输入积分"
          class="price-item"
          @blur="formRef?.validateField('salePrice')"
        >
          <template #append>
            <el-select
              v-model="form.currencyId"
              class="price-item-append"
              placeholder="请选择积分单位"
              @change="() => formRef?.validateField('salePrice')"
            >
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </template>
        </el-input>
        <el-input
          v-model="form.payPrice__yuan"
          class="price-item"
          placeholder="请输入金额（元）"
          @blur="() => formRef?.validateField('salePrice')"
        >
          <template #append>
            元
          </template>
        </el-input>
        <!-- </div> -->
      </el-form-item>

      <el-form-item
        label="配置批次："
        prop="couponBatchTable"
      >
        <el-tabs
          v-model="currentProductTabModel"
          type="border-card"
          :editable="false"
        >
          <el-tab-pane
            v-for="(spec, specIndex) in form.prizeSpecifications"
            :key="specIndex"
            :label="'批次' + (specIndex + 1) + '：'"
            :name="specIndex"
          >
            <el-form-item
              label="优惠券批次："
              class="form-item-spec"
              prop="specSelected"
            >
              <div class="spec-selected-row">
                <el-select
                  v-model="spec.selectedBatch"
                  @change="handleBatchChange"
                >
                  <el-option
                    v-for="item in couponDetail?.batchInfoEntities"
                    :key="item.id"
                    :label="item.couponBatchName"
                    :value="item.id"
                  />
                </el-select>

                <div v-if="spec.selectedBatch">
                  可配置{{ spec.couponTotalNum - spec.couponReceiveNum }}张
                </div>
              </div>
            </el-form-item>

            <el-form-item
              label="批次名称："
              class="form-item-spec"
              prop="specName"
            >
              <el-input
                v-model="spec.name"
                placeholder="请输入批次名称"
                show-word-limit
                maxlength="100"
                @blur="() => formRef?.validateField('couponBatchTable')"
              />
            </el-form-item>

            <el-form-item
              label="使用开始时间："
              class="form-item-spec"
            >
              <template v-if="spec.takeEffectType === 0">
                领取后立即使用
              </template>
              <template v-if="spec.takeEffectType === 1">
                领取后第二天可使用
              </template>
            </el-form-item>

            <el-form-item
              label="使用结束时间："
              class="form-item-spec"
            >
              <template v-if="spec.useType === 0">
                固定时间内均可使用
              </template>
              <template v-if="spec.useType === 1">
                相对开始时间 {{ spec.useDayNum }} 天内可使用 (1 表示当天失效)
              </template>
              <template v-if="spec.useType === 2">
                相对开始时间 {{ spec.useMonthNum }} 月内可使用(1 表示当月月底失效,2表示次月月底失效,依此类推)
              </template>
            </el-form-item>

            <el-form-item
              label="库存："
              class="form-item-spec"
              prop="specAddOrDeductionStockCount"
            >
              剩余库存：{{ spec?.stock ?? 0 }} | 总库存：{{ spec?.totalStock ?? 0 }}
            </el-form-item>

            <el-form-item
              label="设置库存："
              class="form-item-spec"
            >
              <count-adjust
                v-model="spec.addOrDeductionStockCount"
                show-symbol="+-"
                @change="() => formRef?.validateField('couponBatchTable')"
              />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form-item>

      <LimitedPrizeFormItem
        v-model="form"
        :pool-type="form.poolType"
        :type="form.type"
      />

      <!-- 抽奖特有属性 -->
      <LotteryPrizeFormItem
        v-if="form.poolType === 1"
        v-model="form"
      />

      <el-form-item
        label="状态："
        prop="status"
      >
        <el-switch
          v-model="form.onlineStatus"
          inline-prompt
          active-text="上架"
          inactive-text="下架"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>

      <el-form-item prop="auditStatus">
        <template #label>
          <div class="audit-label">
            <span>商品审核：</span>
            <el-popover
              placement="bottom"
              :width="200"
              trigger="hover"
              content="开启后，用户兑换该商品，需要经过您的审核，审核通过的用户可以领取，审核拒绝则领取失败"
            >
              <template #reference>
                <!-- <span class="question-icon">?</span> -->
                <el-icon><QuestionFilled /></el-icon>
              </template>
            </el-popover>
          </div>
        </template>
        <div>
          <el-switch
            v-model="form.verifyFlag"
            active-text="开启"
            inactive-text="关闭"
            inline-prompt
            :active-value="1"
            :inactive-value="0"
          />
          <div class="tips">
            开启后,及时前往“订单管理-审核订单”进行审核
          </div>
        </div>
      </el-form-item>

      <el-form-item
        prop="description"
        label="使用说明："
      >
        <el-input
          v-model="form.description"
          placeholder="请输入使用说明"
          type="textarea"
          :row="5"
        />
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script setup lang="ts">
import type { Ref } from "vue"
import type { ICouponSelectorRow } from "@/api/modules/marketingTool"
import type { IActivityCouponDefineInfo } from "@/api/modules/activity"
import type { InternalRuleItem } from 'async-validator';

import moment from "moment"
import { positiveInteger, positiveNumber_decimal$2, positiveInteger_0  } from "@/utils/commonRegexp" 
import { useCouponUseRange } from "@/views/marketingTool/compositions/useCouponUseRange"
import { getCouponDefineInfo } from "@/api/activity"
import CountAdjust from "@/components/goodsCenter/common/CountAdjust.vue"
import { useCouponType } from "@/views/marketingTool/compositions/useCouponType"
// import { useMallConfig } from "@/views/pointsMall/compositions/useMallConfig"
import marketingCenterApi from "@/api/marketingCenterApi";
import LimitedPrizeFormItem from "./components/LimitedPrizeFormItem.vue";
import LotteryPrizeFormItem from "./components/LotteryPrizeFormItem.vue";


interface ICouponSettingForm {
  type: "systemCoupon";
  prizeType: 4;
  goodsId: number | null;
  name: string;
  poolType: number;
  onlineStatus: number;
  verifyFlag: number;
  prizeSpecifications: IPrizeSpec[];
  thumbnailUrl: string;
  currencyNum: string | number;
  payPrice__yuan: string | number;
  payPrice: string | number | null;
  currencyId: number | null;
  description: string;
  productLimit: string | number | null;
  stock: number;
  stockTotal: number;
}

interface IPrizeSpec {
  goodsId: number;
  goodsSpeId: number;
  id: number | null;
  couponDefineId: number;
  name: string | undefined;
  selectedBatch: number | undefined;
  addOrDeductionStockCount: string | number;
  useType: number | undefined;
  useDayNum: number | undefined;
  useMonthNum: number | undefined;
  takeEffectType: number | undefined;
  stock: number;
  totalStock: number;
  couponTotalNum: number;
  payPrice: number;
  currencyNum: number;
  currencyId: number;
  couponReceiveNum: number;
}


const props = defineProps<{
  show: boolean;
  detail: {
    goodsId: number;
    couponDetail: ICouponSelectorRow;
  },
  mode: "create" | "edit"
}>()

const emits = defineEmits<{
  (e: "update:show", value: boolean): void;
  (e: "update", value: ICouponSettingForm): void
}>()

const { getCouponTypeName } = useCouponType()
const { getCouponUseRangeLabel } = useCouponUseRange()
// const { mallConfig } = useMallConfig()

const showModel = computed({
  get: () => props.show,
  set: (val) => emits("update:show", val)
})

const mode = computed(() => props.mode)

const DefaultCouponThumbnailUrl = 'https://minio.lianhaikeji.com/marketing/pointsMall/1694423169000eYRkFD6J.png'

const formRef = ref()
const formRules = ref({
  name: [ {
    required: true,
    message: "请输入优惠券名称",
    trigger: 'blur'
  } ],
  thumbnailUrl: [ {
    required: true,
    message: "请上传优惠券图片",
    trigger: "change"
  } ],
  salePrice: [ {
    required: true,
    validator(rule: InternalRuleItem, value: number, callback: (e?: Error | string) => void) {
      if (!positiveInteger_0.test('' + form.value.currencyNum)) {
        callback('积分需大于等于0')
        return
      }

      if (!positiveNumber_decimal$2.test('' + form.value.payPrice__yuan)) {
        callback('金额需大于0，且保留2位小数')
        return
      }

      if (!form.value.currencyId) {
        callback("请选择积分单位")
        return
      }

      callback()
    }
  } ],
  couponBatchTable: [ {
    required: true,
    validator(rule: InternalRuleItem, value: number, callback: (e?: Error | string) => void) {
      let verifyFlag = -1
      for (let i = 0; i < form.value.prizeSpecifications.length; i++) {
        const spec = form.value.prizeSpecifications[i]
        const _batchIdentifier = `批次${i + 1}`

        if (!spec.name) {
          callback(`请填写${_batchIdentifier}中的批次名称`)
          verifyFlag = i
          break;
        }

        // 新建时必填，编辑时输入任意字符就校验
        if (mode.value === 'create' || (mode.value === 'edit' && !isEmpty(spec.addOrDeductionStockCount))) {
          if (!positiveInteger_0.test('' + Math.abs(Number(spec.addOrDeductionStockCount)))) {
            callback(`${_batchIdentifier}中设置的库存需为整数`)
            verifyFlag = i
            break;
          }

          if (Number(spec.addOrDeductionStockCount) > (Number(spec.couponTotalNum) - Number(spec.couponReceiveNum))) {
            callback(`${_batchIdentifier}中设置的库存不能大于可配置库存`)
            verifyFlag = i
            break;
          }
        }
      }

      if (verifyFlag > -1) {
        currentProductTabModel.value = verifyFlag
        return
      }

      callback()
    }
  } ],
  productLimit: [ {
    required: true,
    validator(rule: InternalRuleItem, value: number, callback: (e?: Error | string) => void) {
      if (!positiveInteger.test('' + form.value.productLimit)) {
        callback(`领取次数需为正整数`)
        return
      }

      callback()
    }
  } ]
})

const form:Ref<ICouponSettingForm> = ref({
  type: "systemCoupon", // 优惠券固定值
  prizeType: 4, // 优惠券固定值
  poolType: null,
  onlineStatus: 0,
  verifyFlag: 0,
  name: "",
  prizeSpecifications: [ {} ], // 批次
  thumbnailUrl: "",
  currencyNum: "",
  payPrice__yuan: null, // 临时变量
  payPrice: null,
  currencyId: "",
  description: "",
  goodsId: null,
  productLimit: null,
})

const currentProductTabModel = ref(0)

// 批次选择
const handleBatchChange = (value: number) => {
  const _batchInfo = couponDetail.value.batchInfoEntities.find(item => item.id === value)
  const copiedBatchInfo = JSON.parse(JSON.stringify(_batchInfo))
  
  form.value.prizeSpecifications[currentProductTabModel.value] = {
    ...copiedBatchInfo, // 批次信息
    name: copiedBatchInfo.couponBatchName,
    ...form.value.prizeSpecifications[currentProductTabModel.value], // 原先的配置信息
  }

  formRef.value.validateField('couponBatchTable')
} 


const handleBlur = (assignObject: ICouponSettingForm, key: string) => {
  if (assignObject[key] !== null && assignObject[key] !== undefined) {
    assignObject[key] = assignObject[key].trim()
  }
}

const formatTime = (timestamp: number) => {
  return timestamp ? moment(timestamp).format("YYYY.MM.DD HH:mm:ss") : ''
}

const isEmpty = (val:unknown) => val === undefined || val === null || val === ""

const submitLoading = ref(false)
const saveCouponSetting = () => {
  console.log("提交！！！")
  console.log("form", form.value)
  formRef.value?.validate((valid: boolean) => {
    console.log("验证！！！", valid)
    if (valid) {
      console.log("验证通过", valid)

      form.value.prizeSpecifications.forEach(item => {
        item.goodsSpeId = item?.goodsSpeId || item?.id
        item.goodsId = item.couponDefineId

        if (props.mode === 'create') {
          item.id = null // 新增时不能带id
        }

        item.stock = Number(item?.stock ?? 0) + Number(item.addOrDeductionStockCount)
        item.totalStock = item.stock // totalStock 和 stock 一致
        
        item.payPrice = Number(form.value.payPrice__yuan) * 100
        item.currencyNum = Number(form.value.currencyNum)
        item.currencyId = form.value.currencyId!
      })

      form.value.payPrice = Number(form.value.payPrice__yuan) * 100
      form.value.stock = form.value.prizeSpecifications[0].stock
      form.value.stockTotal = form.value.prizeSpecifications[0].totalStock


      console.log("验证通过 => form", form.value)
      emits("update", JSON.parse(JSON.stringify(form.value)))
      showModel.value = false;
    }
  })
}

// 积分类型
const typeList:Ref<{id: number; name: string}[]> = ref([])
const getCurrencyPager = async() => {
  const rs = await marketingCenterApi.currencyPager({
    currentPage: 1,
    showCount: -1,
    status: 1,
  })
  if (rs.code === 200) {
    typeList.value = rs.payload ?? []
  }
}

const couponDetail:Ref<IActivityCouponDefineInfo | undefined> = ref()
const _getCouponDetail = async (couponDefineId: number) => {
  const rs = await getCouponDefineInfo({
    id: couponDefineId,
  })

  if (rs.code !== 200) {
    return
  }

  couponDetail.value = rs.payload
  if (couponDetail.value) {
    couponDetail.value.batchInfoEntities = couponDetail.value?.batchInfoEntities ?? []
    couponDetail.value.discountRule = JSON.parse(rs.payload?.discountRule ?? '')
  }
}

// 创建
const echoFormForCreate = () => {
  Object.keys(props.detail).forEach((key: string) => {
    form.value[key] = props.detail[key]
  })

  form.value.name = couponDetail.value?.couponName ?? ''
  form.value.goodsId = couponDetail.value?.id
  form.value.thumbnailUrl = DefaultCouponThumbnailUrl
  form.value.onlineStatus = couponDetail.value?.isOnline
  console.log("echo create form =>", form.value)
}

// 编辑
const echoFormForEdit = () => {
  console.log("echo edit detail", props.detail)
  Object.keys(props.detail).forEach((key: string) => {
    form.value[key] = props.detail[key]
  })

  form.value.payPrice__yuan = Number(form.value.payPrice) / 100
  form.value.prizeSpecifications.forEach((item) => {
    item.selectedBatch = item.goodsSpeId
    handleBatchChange(item.selectedBatch)
  })
  console.log("echo edit =>", form.value)
}

const handleOpened = async () => {
  getCurrencyPager()

  if (props.mode === 'create') {
    await _getCouponDetail(props.detail.couponDetail.id)
    echoFormForCreate()
  } else {
    console.log("coupon setting edit => ", props.detail)
    await _getCouponDetail(props.detail.goodsId)
    echoFormForEdit()
  }
}

const handleClosed = () => {
  formRef.value.resetFields()
  formRef.value.clearValidate()
}

</script>

<style scoped lang="scss">
.collpase-title {
  position: relative;
  padding-left: 10px;
  font-size: 16px;
  margin-bottom: 20px;

  &::before {
    content: "";
    display: block;
    width: 2px;
    height: 16px;
    border-radius: 2px;
    background-color: var(--el-color-primary);
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
  }

  span {
    font-size: 13px;
    color: #909399;
    margin-left: 10px;
    font-weight: normal;
  }
}

.inline-form-item {
  display: inline-flex;
  align-items: center;
  word-break: keep-all;
}

.audit-label {
  display: flex;
  align-items: center;
}

:deep(.el-tabs) {
  flex: 1;

  .el-tabs__new-tab {
    margin: 10px;
  }
}

:deep(.form-item-price) {
  display: flex;
  
  .price-item {
    flex: 1;
  }

  .price-item:not(:first-child) {
    margin-left: 10px;
  }
  
  .price-item-append {
    width: 150px;
  }
}

:deep(.form-item-spec) {
  margin-bottom: 18px;

  .spec-selected-row {
    display: flex;
    align-items: center;

    >div {
      margin-right: 10px;
    }
  }
}
</style>